import { PropsWithChildren, useEffect, useRef } from 'react'
import {
  Animated,
  StyleSheet,
  View,
  ViewStyle,
  ActivityIndicator,
} from 'react-native'
interface OwlLoadingWrapProp {
  style?: ViewStyle
  loading: boolean
  coverStyle?: ViewStyle
}
export default function OwlLoadingWrap(
  props: PropsWithChildren<OwlLoadingWrapProp>,
) {
  const animatedValue = useRef(new Animated.Value(0)).current
  useEffect(() => {
    Animated.timing(animatedValue, {
      toValue: props.loading ? 1 : 0,
      duration: 250,
      useNativeDriver: false,
    }).start()
  }, [props.loading])
  return (
    <View style={[style.loadingWrap, props.style]}>
      <Animated.View
        style={[
          style.loadingBox,
          props.coverStyle,
          { zIndex: props.loading ? 2 : 0 },
          { opacity: animatedValue },
        ]}
      >
        <View style={style.loadingSize}>
          <ActivityIndicator animating={props.loading} color="#73d7f7" />
        </View>
      </Animated.View>
      {props.children}
    </View>
  )
}

const style = StyleSheet.create({
  loadingWrap: {
    position: 'relative',
  },
  loadingBox: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    zIndex: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.48)',
    top: 0,
    left: 0,
  },
  loadingSize: {
    width: 24,
    height: 24,
  },
})
